package cn.edu.tju.elm.service;

import cn.edu.tju.core.model.User;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.model.Business;
import cn.edu.tju.elm.model.Cart;
import cn.edu.tju.elm.model.Food;
import cn.edu.tju.elm.repository.BusinessRepository;
import cn.edu.tju.elm.repository.CartRepository;
import cn.edu.tju.elm.repository.FoodRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class CartService {

    @Autowired
    private CartRepository cartRepository;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private FoodRepository foodRepository;
    
    @Autowired
    private BusinessRepository businessRepository;

    /**
     * 添加购物车项
     * @param cart 购物车项
     * @return 保存后的购物车项
     */
    public Cart addCartItem(Cart cart) {
        // 验证必要字段
        if (cart.getQuantity() == null || cart.getQuantity() <= 0) {
            throw new IllegalArgumentException("商品数量必须大于0");
        }
        
        // 自动填充customer和business信息
        if (cart.getCustomer() == null) {
            // 从当前认证用户获取customer信息
            User currentUser = userService.getUserWithAuthorities().orElse(null);
            if (currentUser != null) {
                cart.setCustomer(currentUser);
            } else {
                throw new IllegalArgumentException("用户未认证或不存在");
            }
        }
        
        // 从food获取business信息
        if (cart.getFood() != null && cart.getFood().getId() != null) {
            Optional<Food> foodOpt = foodRepository.findById(cart.getFood().getId());
            if (foodOpt.isPresent()) {
                Food food = foodOpt.get();
                cart.setFood(food);
                cart.setBusiness(food.getBusiness());
            } else {
                throw new IllegalArgumentException("指定的商品不存在");
            }
        } else {
            throw new IllegalArgumentException("商品不能为空");
        }
        
        // 检查是否已存在相同商品的购物车项
        Optional<Cart> existingCart = findExistingCartItem(cart);
        
        if (existingCart.isPresent()) {
            // 如果存在，更新数量
            Cart existing = existingCart.get();
            existing.setQuantity(existing.getQuantity() + cart.getQuantity());
            return cartRepository.save(existing);
        } else {
            // 如果不存在，创建新的购物车项
            return cartRepository.save(cart);
        }
    }

    /**
     * 查找用户已有的购物车项
     * @param cart 购物车项
     * @return 已存在的购物车项
     */
    private Optional<Cart> findExistingCartItem(Cart cart) {
        return cartRepository.findAll().stream()
                .filter(c -> c.getCustomer().getId().equals(cart.getCustomer().getId())
                        && c.getFood().getId().equals(cart.getFood().getId())
                        && c.getBusiness().getId().equals(cart.getBusiness().getId()))
                .findFirst();
    }

    /**
     * 获取用户的购物车列表
     * @param userId 用户ID
     * @return 购物车项列表
     */
    public List<Cart> getCartItemsByUserId(Long userId) {
        return cartRepository.findAll().stream()
                .filter(cart -> cart.getCustomer() != null && cart.getCustomer().getId().equals(userId))
                .collect(Collectors.toList());
    }

    /**
     * 更新购物车项数量
     * @param id 购物车项ID
     * @param quantity 新数量
     * @return 更新后的购物车项
     */
    public Cart updateCartItemQuantity(Long id, Integer quantity) {
        Optional<Cart> cartOpt = cartRepository.findById(id);
        if (cartOpt.isPresent()) {
            Cart cart = cartOpt.get();
            cart.setQuantity(quantity);
            return cartRepository.save(cart);
        }
        return null;
    }

    /**
     * 删除购物车项
     * @param id 购物车项ID
     * @return 是否删除成功
     */
    public boolean deleteCartItem(Long id) {
        if (cartRepository.existsById(id)) {
            cartRepository.deleteById(id);
            return true;
        }
        return false;
    }

    /**
     * 清空用户购物车
     * @param userId 用户ID
     * @return 是否清空成功
     */
    public boolean clearUserCart(Long userId) {
        List<Cart> userCarts = getCartItemsByUserId(userId);
        if (!userCarts.isEmpty()) {
            userCarts.forEach(cart -> cartRepository.deleteById(cart.getId()));
            return true;
        }
        return false;
    }
}